<template>
  <a-modal :title="title" :width="1250" :visible="visible"  @cancel="handleCancel"
    :cancelText="$t('systemManagement.close')" wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button :key="currentIndex" style="margin-left: 8px" v-print="`#reportPrintDetail${currentIndex}`" icon="printer">{{$t('reportQuery.print')}}</a-button>   
      <a-button v-if="btnEnableList.indexOf(5) > -1"  style="margin-left: 8px" @click="generatePrintData($event,'ZYHZ-list')" icon="printer">{{$t('inPrint.other') + $t('reportQuery.print')}}</a-button>               
    </template>
    <!-- 查询区域 -->
    
    <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <!-- <a-col :lg="6" :md="12" :sm="24">
                <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('basicInformation.customer')" data-step="1" :data-title="$t('basicInformation.customer')"
                  :data-intro="$t('popup.customerMustUser')">
                  <a-select :placeholder="$t('manuManagement.selectCustomer')" v-model="queryParamDetail.creator"
                    :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                    <div slot="dropdownRender" slot-scope="menu">
                      <v-nodes :vnodes="menu" />
                      <a-divider style="margin: 4px 0;" />
                    </div>
                    <a-select-option v-for="(item,index) in userList" :key="index" :value="item.id">
                      {{ item.userName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col> -->

              <!-- <a-col :md="6" :sm="24">
                <a-form-item :label="$t('reportQuery.documentDate')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-range-picker
                  :disabled="true"
                    style="width: 100%"
                    v-model="queryParam.createTimeRange"
                    :default-value="defaultTimeStr"
                    format="YYYY-MM-DD"
                    :placeholder="[$t('reportQuery.startTime'), $t('reportQuery.endTime')]"
                    @change="onDateChange"
                  />
                </a-form-item>
              </a-col> -->
            </a-row>
            
            <template v-if="toggleSearchStatus">
                 
              </template>
          </a-form>
        </div>
    <!-- table区域-begin -->
      <a-tabs :default-active-key="0" @change="tabsChange">
          <a-tab-pane v-for="(item,index) in list" :key="index" :tab="item.user.loginName" forceRender>
            <section ref="print" :id="`reportPrintDetail${index}`">
            <div style="text-align:center;margin-bottom:10px">Cashier Report - {{ tenantInfo.loginName || '-' }}</div>
            <div  style="text-align:center;margin-bottom:10px">{{ queryParam.beginTime }} ~ {{ queryParam.endTime }}</div>
            <a-table v-if="selectType === 'list'" bordered ref="table" size="middle" :columns="columns"
              :dataSource="item.dataSource"  :loading="loading"
              :selection="{key:'id'}"
              :customRow="rowAction" @change="handleTableChange">
              <span slot="numberCustomRender" slot-scope="text, record">
                <a @click="myHandleDetail(record)">{{ record.number }}</a>
              </span>
            </a-table>
          </section>
          </a-tab-pane>
      </a-tabs>

    <!-- table区域-end -->
    <!-- 表单区域 -->
    <bill-detail ref="billDetail"></bill-detail>
  </a-modal>
</template>

<script>
import BillDetail from '@/views/bill/dialog/BillDetail'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { findBillDetailByNumber,findBySelectSup,findBySelectCus,getUserList  } from '@/api/api'
import { getAction } from '@/api/manage'
import { getNowFormatYear,openDownloadDialog, sheet2blob,filterObj } from "@/utils/util"
import moment from 'moment';
export default {
  name: 'LinkBillList',
  mixins: [JeecgListMixin],
  components: {
    BillDetail ,
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      }
  },
  data() {
    return {
      title: this.$t('otherJS.officeClerkSummary'),
      visible: false,
      disableMixinCreated: true,
      selectedRowKeys: [],
      selectedDetailRowKeys: [],
      selectBillRows: [],
      selectedRows:[],
      selectBillDetailRows: [],
      showType: 'basic',
      selectType: 'list',
      linkNumber: '',
      deliveryMethod: '',
      arrivalTimeStr: '',
      organId: '',
      depotId: '',
      discount: '',
      deposit: '',
      remark: '',
      checkDepotId:'',
      linkId:'',
      supList:[],
      cusList:[],
      list:[],
      userList:[],
      defaultTimeStr:[],
      tenantInfo:{},
      currentIndex:0,
      queryParam: {
      },
      noNeedNextDialogArray: ['ZPHX', 'ZFYS', 'YSKD', 'FYF','YFKD'],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      // 表头
      
      columns: [
        
      {title:this.$t('manuManagement.customer'),align:"left", dataIndex: 'organName',width:50},
          {title:this.$t('purchasingManagement.amount'),align:"left", dataIndex: 'amount',width:50,
            customRender:(t,r,index)=>{
                return this.$sinceCount(t)
            }},
      ],
      dataSource: [],
      dataSourceDetail: [],
      url: {
        list: "/depotHead/getDailySalesDetail",
      }
    }
  },
  created() {
    
  },
  methods: {
    moment,
    initCustomer () {
      let that = this
      findBySelectCus({}).then(res => {
        if (res) {
          that.cusList = res
        }
      })
    },
    /**
     * 
     * @param {obj} params 父组件查询参数
     * @param {string} btnEnableList  权限
     * @param {array} userList 根据租户获取的职员
     */
    show(params,btnEnableList,userList,tenantInfo) {
      this.userList = userList
      this.tenantInfo = tenantInfo
      this.queryParam = Object.assign(this.queryParam,params)
      console.log('this.queryParam :>> ', this.queryParam);
      this.btnEnableList = btnEnableList
      this.loadData(1)
      this.visible = true
    },


    getType: function () {
      const checkboxArr = [];
      if (checkboxArr.includes(this.queryParam.prefixNo)) {
        return 'checkbox'
      }
      return 'radio';
    },

    myHandleDetail(record) { 
      findBillDetailByNumber({ number: record.number }).then((res) => {
        if (res && res.code === 200) {
          let type = res.data.depotHeadType
          type = type.replace('其它', '')
          this.$refs.billDetail.show(res.data, type)
          this.$refs.billDetail.title = type + "-" + '详情'
        }
      })
    },
    setColumns(columns,columnsDetail){
      if(columns && columns.length){
        this.columns = columns
      }
      if(columnsDetail && columnsDetail.length){
        this.columnsDetail = columnsDetail
      }
    },
    close() {
      this.$emit('close');
      this.visible = false;
    },
    handleCancel() {
      this.close()
    },
    onSelectChange(selectedRowKeys,selectedRows) {
      console.log(selectedRowKeys,666);
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows.map(v=>v.id)
    },
    onSelectDetailChange(selectedRowKeys) {
      this.selectedDetailRowKeys = selectedRowKeys;
    },
    organChenge(e){
      let arr = this.dataSourceDetail.filter(v=>v.organId === e)
      this.selectedDetailRowKeys = arr.map(v=>v.id)
    },
    handleOk() {
      
    },
    onDateChange: function (value, dateString) {
        this.$set(this.queryParam,'beginTime',dateString[0])
        this.$set(this.queryParam,'endTime',dateString[1])
        this.loadData(1)
    },
    onDateOk(value) {
      console.log(value);
    },
    searchReset() {
      this.queryParam = {
        organId: undefined,
        creator:undefined,
        beginTime: getNowFormatYear() + '-01-01',
        endTime: moment().format('YYYY-MM-DD'),
      }
      this.loadData(1);
    },
    getSelectBillRows() {
      let dataSource = this.dataSource;
      this.selectBillRows = [];
      for (let i = 0, len = dataSource.length; i < len; i++) {
        if (this.selectedRows.includes(dataSource[i].id)) {
          this.selectBillRows.push(dataSource[i]);
        }
      }
    },
    getSelectBillDetailRows() {
      let dataSource = this.dataSourceDetail;
      this.selectBillDetailRows = [];
      for (let i = 0, len = dataSource.length; i < len; i++) {
        if (this.selectedDetailRowKeys.includes(dataSource[i].id)) {
          this.selectBillDetailRows.push(dataSource[i]);
        }
      }
    },
    rowAction(record, index) {
      return {
        on: {
          click: () => {
            let arr = []
            arr.push(record.id)
            this.selectedRowKeys = arr
          },
          dblclick: () => {
            if (this.noNeedNextDialogArray.includes(this.queryParam.prefixNo)) {
              this.$emit('ok', [record])
              this.close()
              return
            }
            let arr = []
            arr.push(record.id)
            this.selectedRows = arr
            this.handleOk()
          }
        }
      }
    },
    
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      let searchObj = {}
      searchObj.search = JSON.stringify(this.queryParam)
      var param = Object.assign(sqp, searchObj, this.isorter, this.filters)
      param.field = this.getQueryField()
      // param.promotionType = this.promotionType
      param.currentPage = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    
    loadData (arg) {
      console.log(this.url.list, this.title, 'handler: loadData')
      if (!this.url.list) {
        this.$message.error(this.$t('popup.pleaseProperty'))
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.loading = true
      let param = this.getQueryParams()
      getAction(this.url.list, param).then(res => {
        this.loading = false
        if (res.code === 200) {
          this.list = res.data.rows
          this.list.forEach(value=>{
            let dataSource = value.salesUserList || []
            let totalArray = []
            // 零售明细
            let retails = dataSource.filter(v=>v.organType === 1).map(v=>(v.organName = v.organName +' - CASH SALE',v))
            let retailsRefund = dataSource.filter(v=>v.organType === 4).map(v=>(v.organName = v.organName +' - REFUND',v))
            // Cashier Report 零售
            if(retails && retails.length){
              totalArray.push({
               organName:`Cashier Report :   ` + value.user.loginName + `(${value.user.username})`
              
              })
              // push零售明细
              totalArray.push(...retails)
              // 零售退款
              
              totalArray.push(...retailsRefund)
              // 零售汇总
              totalArray.push({
                organName:'Sub Total- Cash Customer',
                amount: retails.concat(retailsRefund).reduce((total,cur)=>{return this.$toDecimal(total+cur.amount)},0)
              })
              totalArray.push({
                organName:'CASH SALES- ACCOUNT CUSTOMER',
              })
              
            }
            
            // 普通客户汇总
            
            // 零售明细
            let normals = dataSource.filter(v=>v.organType === 2).map(v=>(v.organName = v.organName +' - CASH SALE',v))
            
            
            if(normals && normals.length){
              totalArray.push(...normals)

              
            }
            // 用户退款
            let refund = dataSource.filter(v=>v.organType === 3).map(v=>(v.organName = v.organName +' - REFUND',v))
            if(refund && refund.length){
              totalArray.push(...refund)
            }
            if(refund.length || normals.length){
              let cashAll = dataSource.filter(v=>[2,3].includes(v.organType))
              // 零售汇总
              totalArray.push({
                organName:'Sub Total- Cash Account Customer',
                amount: cashAll.reduce((total,cur)=>{return this.$toDecimal(total+cur.amount)},0)
              })
            }
            const getTotalPayment = (arr,columnKey,str)=>{
                return arr.filter(v=>str.indexOf(v.organName) > -1).reduce((total,item)=>{return this.$toDecimal(total + item[columnKey])},0)
            }
            
            totalArray.push({
                organName:'Total for Cashier',
                amount: getTotalPayment(totalArray,'amount','Sub Total- Cash Customer,Sub Total- Cash Account Customer')
            })
            value.dataSource = totalArray
            value.pagination = {
              pageSize:totalArray.length
            }
          })
          
        }else{
          this.$message.error(res.msg || res.data)
        }
      })
    },
    
    tabsChange(index){
      this.currentIndex = index
    },
    initUser () {
        getUserList({}).then((res) => {
          this.userList = res
        })
      },
      
    /**
     * 
     * @param {string} name 模板名称，如果是列表的详情就需要传，因为无法通过路由获取
     */
    generatePrintData(event,name){
      const Cols = this.columns.map(v=>{
        let item ={
          name: v.title,
          required: false,
          size: 255,
          type: "str",
          // key:v.dataIndex
        }
        return item
      })
      const data = this.dataSource.map(v=>{
        let item ={}
        this.columns.forEach(val=>{
          item[val.dataIndex] = v[val.dataIndex]
        })
        return item ;
      })
      // 表体数据
      let table = {
        Tables:[]
      }
      this.list.forEach((val,idx)=>{ 
        table.Tables[idx] = {
          Cols:Cols,
          Data:val.dataSource,
          Name:'table'
        }
      })
      // 表头数据
      let ColHead = []

      for (let key in this.queryParam) {
        ColHead.push({
          name: key,
          required: false,
          size: 255,
          type: "str",
        })
      }
      table.Tables[this.list.length] = {
        Cols:ColHead,
        Data:[this.queryParam],
        Name:'headerInfo'
      }
      table.ver=4,
      table.Copies=1,
      table.printer="pdfFactory Pro",
      table.preview=0,
      table.taskid="1234567890",
      table.upload_templ_url="http://192.168.147.1:8081",
      table.upload_templ_user="myname",
      table.upload_templ_password="1234567",
      table.upload_templ_comment = this.$route.name
      table.upload_templ_name = this.$route.name
      const templateFileName = name || getFileNameByKey(this.$route.name,getLanCode() === 'en' ? 'en' : 'text' )
      table.template = `${templateFileName}.fr3`
      console.log('table :>> ', table);
      const Print = require('@/utils/print/cfprint_ext')
      Print.sendMsg(table)
    },
      async exportExcel() {
        let aoa = [this.columns.map(v=>v.title)]
        this.downLoading = true
        // 获取要导出的数据
        let dataSource = await this.loadAllData(1)
        this.downLoading = false
        for (let i = 0; i < dataSource.length; i++) {
          let item = []
          for (let l = 0; l < this.columns.length; l++) {
            let column = this.columns[l]
              let text = dataSource[i][column.dataIndex] || ''
              // 有自定义方法
              if(typeof(column.customRender) ==="function"){
                let res = column.customRender(text,dataSource[i])
                // 返回的是node节点
                if(res && typeof(res.componentOptions)!="undefined"){
                  text = res.componentOptions.children[0].text
                }else{
                  text = res || ''
                }
              }
              item.push(text)
            
          }
          aoa.push(item)
        }
        openDownloadDialog(sheet2blob(aoa),this.title)
      },
  }
}
</script>

<style scoped>

</style>